/*
 * Powered By cuichen
 * Since 2014 - 2018
 */
package com.seeyoui.kensite.bussiness.orderlang.delivery.controller;

import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.seeyoui.kensite.common.util.DateUtils;
import com.seeyoui.kensite.common.constants.StringConstant;
import com.seeyoui.kensite.common.base.domain.EasyUIDataGrid;
import com.seeyoui.kensite.common.base.controller.BaseController;
import com.seeyoui.kensite.common.util.RequestResponseUtil;
import com.seeyoui.kensite.common.util.excel.ExportExcel;

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.lucene.index.Term;
import org.apache.shiro.authz.annotation.RequiresPermissions;

import com.seeyoui.kensite.common.base.domain.Page;
import com.seeyoui.kensite.framework.luence.domain.LuceneDocument;
import com.seeyoui.kensite.framework.luence.util.LuceneUtils;
import com.seeyoui.kensite.framework.system.domain.SysUser;
import com.seeyoui.kensite.framework.system.util.UserUtils;
import com.seeyoui.kensite.bussiness.orderlang.delivery.domain.Delivery;
import com.seeyoui.kensite.bussiness.orderlang.delivery.domain.DeliveryExamineProductVO;
import com.seeyoui.kensite.bussiness.orderlang.delivery.domain.DeliveryExamineTitleVO;
import com.seeyoui.kensite.bussiness.orderlang.delivery.domain.DeliveryVO;
import com.seeyoui.kensite.bussiness.orderlang.delivery.service.DeliveryService;
import com.seeyoui.kensite.bussiness.orderlang.deliveryProduct.domain.DeliveryProduct;
import com.seeyoui.kensite.bussiness.orderlang.deliveryProduct.service.DeliveryProductService;
import com.seeyoui.kensite.bussiness.orderlang.outbound.domain.Outbound;
import com.seeyoui.kensite.bussiness.orderlang.outbound.service.OutboundService;
import com.seeyoui.kensite.bussiness.orderlang.productPrice.domain.ProductPrice;
import com.seeyoui.kensite.bussiness.orderlang.productPrice.service.ProductPriceService;
import com.seeyoui.kensite.bussiness.orderlang.productSpec.domain.ProductSpec;
import com.seeyoui.kensite.bussiness.orderlang.productSpec.service.ProductSpecService;
/**
 * Delivery
 * @author cuichen
 * @version 2.0
 * @since 1.0
 * @date 2018-03-01
 */

@Controller
@RequestMapping(value = "delivery")
public class DeliveryController extends BaseController {
	
	@Autowired
	private DeliveryService deliveryService;
	@Autowired
    private ProductPriceService productPriceService;
	@Autowired
    private ProductSpecService productSpecService;
	@Autowired
    private OutboundService outboundService;
	@Autowired
    private DeliveryProductService deliveryProductService;
	/**
	 * 展示列表页面
	 * @param modelMap
	 * @param module
	 * @return
	 * @throws Exception
	 */
	//@RequiresPermissions("userCart:delivery:view")
	@RequestMapping(value = "/{page}")
	public ModelAndView view(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, @PathVariable String page) throws Exception {
		return new ModelAndView("bussiness/orderlang/delivery/"+page, modelMap);
	}
	
	/**
     * 加载审批列表头部信息
     * @param modelMap
     * @param module
     * @return
     * @throws Exception
     */
	@RequestMapping(value = "/deliveryDetailForTitle", method=RequestMethod.POST)
    @ResponseBody
    public Object deliveryDetailForTitle(HttpSession session,
            HttpServletResponse response, HttpServletRequest request,
            ModelMap modelMap, String deliveryId) throws Exception {
        DeliveryExamineTitleVO deliveryExamineVO = deliveryService.findDeliveryDetailForTitle(deliveryId);
        return deliveryExamineVO;
    }
	
	/**
     * 加载审批列表商品信息
     * @param modelMap
     * @param module
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/deliveryDetailForProduct", method=RequestMethod.POST)
    @ResponseBody
    public Object deliveryDetailForProduct(HttpSession session,
            HttpServletResponse response, HttpServletRequest request,
            ModelMap modelMap, String deliveryId) throws Exception {
        List<DeliveryExamineProductVO> deliveryExamineProductVOList = deliveryService.findDeliveryDetailForProduct(deliveryId);
        for (DeliveryExamineProductVO deliveryExamineProductVO : deliveryExamineProductVOList) {
            ProductSpec productSpec = new ProductSpec();
            productSpec.setProductPriceId(deliveryExamineProductVO.getProductPriceId());
            List productSpecList = productSpecService.findList(productSpec);
            deliveryExamineProductVO.setProductSpecList(productSpecList);
        }
        return deliveryExamineProductVOList;
    }
	
	/**
	 * 根据ID查询单条数据
	 * @param modelMap
	 * @param module
	 * @return
	 * @throws Exception
	 */
	//@RequiresPermissions("userCart:delivery:select")
	@RequestMapping(value = "/data/{id}")
	@ResponseBody
	public Object data(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, @PathVariable String id) throws Exception {
		Delivery delivery = deliveryService.findOne(id);
		return delivery;
	}
	
	/**
	 * 根据ID查询单条数据并返回相应表单
	 * @param modelMap
	 * @param module
	 * @return
	 * @throws Exception
	 */
	//@RequiresPermissions("userCart:delivery:view")
	@RequestMapping(value = "/form/{page}/{id}")
	public ModelAndView form(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, @PathVariable String page, @PathVariable String id) throws Exception {
		Delivery delivery = deliveryService.findOne(id);
		modelMap.put("delivery", delivery);
		return new ModelAndView("bussiness/orderlang/delivery/"+page, modelMap);
	}
	
	/**
	 * 获取列表展示数据
	 * @param modelMap
	 * @param delivery
	 * @return
	 * @throws Exception
	 */
	//@RequiresPermissions("userCart:delivery:select")
	@RequestMapping(value = "/list/data", method=RequestMethod.POST)
	@ResponseBody
	public Object listData(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, Delivery delivery) throws Exception {
		List<Delivery> deliveryList = deliveryService.findList(delivery);
		int total = deliveryService.findTotal(delivery);
		EasyUIDataGrid eudg = new EasyUIDataGrid();
		eudg.setTotal(String.valueOf(total));
		eudg.setRows(deliveryList);
		return eudg;
	}
	
	/**
     * 获取列表展示数据带分页器用于jsp自己做分页
     * @param modelMap
     * @param delivery
     * @return
     * @throws Exception
     */
    //@RequiresPermissions("warehouse:delivery:view")
    @RequestMapping(value = "/list/page", method=RequestMethod.POST)
    @ResponseBody
    public Object listPage(HttpSession session,
            HttpServletResponse response, HttpServletRequest request,
            ModelMap modelMap, Delivery delivery, String orderId, String beginTime, String endTime) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("orderId", orderId);
        map.put("beginTime", beginTime);
        map.put("endTime", endTime);
        map.put("row", delivery.getRow());
        map.put("rows", delivery.getRows());
        List<DeliveryVO> deliveryList = deliveryService.findListRelationOrder(map);
        int total = deliveryService.findTotalRelationOrder(map);
        Page<Delivery> page = new Page<Delivery>(delivery.getPage(), delivery.getRows(), total);
        Map<String, Object> dataMap = new HashMap<String, Object>();
        dataMap.put("rows", deliveryList);
        dataMap.put("page", page);
        return dataMap;
    }
	
	/**
	 * 获取所有数据
	 * @param modelMap
	 * @param delivery
	 * @return
	 * @throws Exception
	 */
	//@RequiresPermissions("userCart:delivery:select")
	@RequestMapping(value = "/list/all", method=RequestMethod.POST)
	@ResponseBody
	public Object listAll(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, Delivery delivery) throws Exception {
		List<Delivery> deliveryList = deliveryService.findAll(delivery);
		return deliveryList;
	}
	
	/**
     * 订单详情界面加载发货单信息
     * @param modelMap
     * @param delivery
     * @return
     * @throws Exception
     */
    //@RequiresPermissions("userCart:delivery:select")
    @RequestMapping(value = "/orderDetailForDelivery", method=RequestMethod.POST)
    @ResponseBody
    public Object orderDetailForDelivery(HttpSession session,
            HttpServletResponse response, HttpServletRequest request,
            ModelMap modelMap, Delivery delivery) throws Exception {
        List<Delivery> deliveryList = deliveryService.findAll(delivery);
        return deliveryList;
    }
	
	/**
	 * 保存新增的数据
	 * @param modelMap
	 * @param delivery
	 * @return
	 * @throws Exception
	 */
	//@RequiresPermissions("userCart:delivery:insert")
	@RequestMapping(value = "/save", method=RequestMethod.POST)
	@ResponseBody
	public String save(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, Delivery delivery) throws Exception {
		if (!beanValidator(modelMap, delivery)){
			RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.FALSE);
			return null;
		}
		deliveryService.save(delivery);
		RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.TRUE);
		return null;
	}
	
	/**
     * 审批发货单
     * @param modelMap
     * @param delivery
     * @return
     * @throws Exception
     */
    //@RequiresPermissions("userCart:delivery:insert")
    @RequestMapping(value = "/deliveryExamine", method=RequestMethod.POST)
    @ResponseBody
    public String deliveryExamine(HttpSession session,
            HttpServletResponse response, HttpServletRequest request,
            ModelMap modelMap, String deliveryId, String approveMemo, String approve) throws Exception {
        Delivery delivery = deliveryService.findOne(deliveryId);
        if(null != delivery){
            try {
                SysUser sysUser = UserUtils.getUser();// 获取当前系统登陆人
                delivery.setApproveTime(new Date());
                delivery.setApproveId(sysUser.getId());
                delivery.setApproveMemo(approveMemo);
                delivery.setApprove(approve);
                deliveryService.update(delivery);
            } catch (Exception e) {
                modelMap.put("message", "审批失败！");
                RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.TRUE);
                return null;
            }
        }else{
            modelMap.put("message", "审批失败！");
            RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.TRUE);
            return null;
        }
        modelMap.put("message", "审批成功！");
        RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.TRUE);
        return null;
    }
	
	/**
     * 保存新增的数据
     * @param modelMap
     * @param delivery
     * @return
     * @throws Exception
     */
    //@RequiresPermissions("userCart:delivery:insert")
    @RequestMapping(value = "/saveDelivery", method=RequestMethod.POST)
    @ResponseBody
    public String saveDelivery(HttpSession session,
            HttpServletResponse response, HttpServletRequest request,
            ModelMap modelMap, String jsonData,String orderId) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyymmddHHMMSSS");
        jsonData = StringEscapeUtils.unescapeHtml(jsonData);// 去除字符串中的乱码字符
        JSONArray jsonDataArray = JSON.parseArray(jsonData);// 将字符串转换为JSON对象数组
        
        // 获取当前登陆人对象
        SysUser sysUser = UserUtils.getUser();
        // 创建发货单对象
        Delivery delivery = new Delivery();
        delivery.setOrderId(orderId);
        delivery.setDeliveryCode(sdf.format(new Date())+((int)((Math.random()*9+1)*1000)));
        delivery.setCreatorId(sysUser.getId());
        delivery.setCreateTime(new Date());
        delivery.setApprove("0");
        delivery.setStatus("0");
        deliveryService.save(delivery);
        for (Iterator iterator = jsonDataArray.iterator(); iterator.hasNext();) {
            JSONObject jsonObj = (JSONObject) iterator.next();
            String productPriceId = jsonObj.get("productPriceId").toString();
            // 查询商品价格明细
            ProductPrice productPrice = productPriceService.findOne(productPriceId);
            String quantity = jsonObj.get("quantity").toString();
            DeliveryProduct deliveryProduct = new DeliveryProduct();
            deliveryProduct.setDeliveryId(delivery.getId());
            deliveryProduct.setProductId(productPrice.getProductId());
            deliveryProduct.setProductPriceId(productPriceId);
            deliveryProduct.setQuantity(quantity);
            deliveryProductService.save(deliveryProduct);
        }
        modelMap.put("message", "发货单创建成功");
        RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.TRUE);
        return null;
    }
	
	/**
	 * 保存修改的数据
	 * @param modelMap
	 * @param delivery
	 * @return
	 * @throws Exception
	 */
	//@RequiresPermissions("userCart:delivery:update")
	@RequestMapping(value = "/update", method=RequestMethod.POST)
	@ResponseBody
	public String update(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, Delivery delivery) throws Exception {
		if (!beanValidator(modelMap, delivery)){
			RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.FALSE);
			return null;
		}
		deliveryService.update(delivery);
		RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.TRUE);
		return null;
	}
	
	/**
	 * 删除数据库
	 * @param modelMap
	 * @param deliveryId
	 * @return
	 * @throws Exception
	 */
	//@RequiresPermissions("userCart:delivery:delete")
	@RequestMapping(value = "/delete", method=RequestMethod.POST)
	@ResponseBody
	public String delete(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, String id) throws Exception {
		List<String> listId = Arrays.asList(id.split(","));
		deliveryService.delete(listId);
		RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.TRUE);
		return null;
	}
	
	/**
	 * 假删除
	 * @param modelMap
	 * @param delivery
	 * @return
	 * @throws Exception
	 */
	//@RequiresPermissions("userCart:delivery:delete")
	@RequestMapping(value = "/remove", method=RequestMethod.POST)
	@ResponseBody
	public String remove(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, Delivery delivery) throws Exception {
		deliveryService.remove(delivery);
		RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.TRUE);
		return null;
	}

	/**
	 * 导出Excel数据
	 * @param modelMap
	 * @param delivery
	 * @return
	 * @throws Exception
	 */
	//@RequiresPermissions("userCart:delivery:export")
	@RequestMapping(value = "/export")
	public String export(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, Delivery delivery) throws Exception {
		String fileName = DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
		List<Delivery> deliveryList = deliveryService.findAll(delivery);
		new ExportExcel(null, Delivery.class).setDataList(deliveryList).write(response, fileName).dispose();
		return null;
	}
}